class TrustSyncManager {
  constructor() {
    this.syncSettings = {
      autoSync: false, // 默认关闭自动同步，避免移动端问题
      syncInterval: 300000, // 5分钟
      conflictStrategy: 'ask', // ask, local, remote, merge
      dataEncryption: true,
      syncServer: 'https://api.trust-sync.com', // 示例服务器
      apiKey: null
    }
    
    this.syncHistory = []
    this.conflicts = []
    this.isOnline = false
    this.lastSyncTime = null
    this.syncInProgress = false
    
    // 延迟初始化，避免启动时的错误
    setTimeout(() => {
      this.initializeSync()
    }, 1000)
  }
  
  // 初始化同步
  async initializeSync() {
    try {
      // 加载设置
      await this.getSyncSettings()
      
      // 检查网络状态
      this.isOnline = await this.checkNetworkStatus()
      
      // 检查连接
      if (this.isOnline) {
        await this.checkConnection()
      }
      
      // 开始自动同步
      if (this.syncSettings.autoSync) {
        this.startAutoSync()
      }
      
    } catch (error) {
      console.error('Failed to initialize sync:', error)
    }
  }
  
  // 检查网络状态
  async checkNetworkStatus() {
    try {
      // 在UniApp中，可以使用uni.getNetworkType()检查网络状态
      const networkType = await new Promise((resolve) => {
        uni.getNetworkType({
          success: (res) => resolve(res.networkType),
          fail: () => resolve('none')
        })
      })
      
      return networkType !== 'none'
    } catch (error) {
      console.error('Failed to check network status:', error)
      return false
    }
  }
  
  // 检查连接
  async checkConnection() {
    if (!this.syncSettings.syncServer) {
      return false // 没有配置服务器时直接返回 false
    }
    try {
      const response = await this.makeRequest('GET', '/health')
      return response.status === 200
    } catch (error) {
      console.log('Connection check failed (silent):', error)
      return false
    }
  }
  
  // 同步数据
  async syncData() {
    if (this.syncInProgress) {
      return { success: false, error: '同步正在进行中' }
    }
    
    try {
      this.syncInProgress = true
      
      // 检查网络状态
      if (!this.isOnline) {
        throw new Error('网络不可用')
      }
      
      // 获取本地数据
      const localData = await this.getLocalData()
      
      // 获取远程数据
      const remoteData = await this.getRemoteData()
      
      // 比较数据并处理冲突
      const syncResult = await this.processSyncData(localData, remoteData)
      
      // 更新本地数据
      if (syncResult.localUpdates.length > 0) {
        await this.updateLocalData(syncResult.localUpdates)
      }
      
      // 更新远程数据
      if (syncResult.remoteUpdates.length > 0) {
        await this.updateRemoteData(syncResult.remoteUpdates)
      }
      
      // 记录同步历史
      this.recordSyncHistory('success', '数据同步成功', {
        localUpdates: syncResult.localUpdates.length,
        remoteUpdates: syncResult.remoteUpdates.length
      })
      
      this.lastSyncTime = Date.now()
      
      return { success: true, result: syncResult }
      
    } catch (error) {
      console.error('Sync failed:', error)
      
      this.recordSyncHistory('error', '同步失败', {
        error: error.message
      })
      
      return { success: false, error: error.message }
    } finally {
      this.syncInProgress = false
    }
  }
  
  // 获取本地数据
  async getLocalData() {
    try {
      const data = {}
      
      // 获取信任卡牌数据
      const trustCards = uni.getStorageSync('trustCardsData')
      if (trustCards) {
        data.trustCards = JSON.parse(trustCards)
      }
      
      // 获取信任仪表盘数据
      const dashboardData = uni.getStorageSync('trustDashboardData')
      if (dashboardData) {
        data.dashboard = JSON.parse(dashboardData)
      }
      
      // 获取信任分支数据
      const branchData = uni.getStorageSync('trustBranchData')
      if (branchData) {
        data.branch = JSON.parse(branchData)
      }
      
      // 获取拖拽历史数据
      const dragData = uni.getStorageSync('trustDragHistory')
      if (dragData) {
        data.drag = JSON.parse(dragData)
      }
      
      return data
    } catch (error) {
      console.error('Failed to get local data:', error)
      return {}
    }
  }
  
  // 获取远程数据
  async getRemoteData() {
    try {
      const response = await this.makeRequest('GET', '/data')
      return response.data
    } catch (error) {
      console.error('Failed to get remote data:', error)
      return {}
    }
  }
  
  // 处理同步数据
  async processSyncData(localData, remoteData) {
    const result = {
      localUpdates: [],
      remoteUpdates: [],
      conflicts: []
    }
    
    // 比较各个数据模块
    const modules = ['trustCards', 'dashboard', 'branch', 'drag']
    
    for (const module of modules) {
      const localModule = localData[module] || {}
      const remoteModule = remoteData[module] || {}
      
      const moduleResult = await this.compareModuleData(module, localModule, remoteModule)
      
      result.localUpdates.push(...moduleResult.localUpdates)
      result.remoteUpdates.push(...moduleResult.remoteUpdates)
      result.conflicts.push(...moduleResult.conflicts)
    }
    
    // 处理冲突
    if (result.conflicts.length > 0) {
      await this.handleConflicts(result.conflicts)
    }
    
    return result
  }
  
  // 比较模块数据
  async compareModuleData(module, localData, remoteData) {
    const result = {
      localUpdates: [],
      remoteUpdates: [],
      conflicts: []
    }
    
    // 获取本地时间戳
    const localTimestamp = localData.lastModified || 0
    const remoteTimestamp = remoteData.lastModified || 0
    
    if (localTimestamp > remoteTimestamp) {
      // 本地数据更新，需要上传到远程
      result.remoteUpdates.push({
        module: module,
        data: localData,
        timestamp: localTimestamp
      })
    } else if (remoteTimestamp > localTimestamp) {
      // 远程数据更新，需要下载到本地
      result.localUpdates.push({
        module: module,
        data: remoteData,
        timestamp: remoteTimestamp
      })
    } else if (localTimestamp === remoteTimestamp && localTimestamp > 0) {
      // 时间戳相同，检查内容是否一致
      if (!this.isDataEqual(localData, remoteData)) {
        // 内容不一致，产生冲突
        result.conflicts.push({
          module: module,
          localData: localData,
          remoteData: remoteData,
          timestamp: localTimestamp
        })
      }
    }
    
    return result
  }
  
  // 检查数据是否相等
  isDataEqual(data1, data2) {
    try {
      return JSON.stringify(data1) === JSON.stringify(data2)
    } catch (error) {
      console.error('Failed to compare data:', error)
      return false
    }
  }
  
  // 处理冲突
  async handleConflicts(conflicts) {
    for (const conflict of conflicts) {
      const resolution = await this.resolveConflict(conflict)
      
      if (resolution) {
        this.conflicts.push({
          id: Date.now(),
          type: conflict.module,
          description: `${conflict.module} 数据冲突`,
          timestamp: Date.now(),
          resolution: resolution
        })
      }
    }
  }
  
  // 解决冲突
  async resolveConflict(conflict) {
    const strategy = this.syncSettings.conflictStrategy
    
    switch (strategy) {
      case 'local':
        return 'local'
      case 'remote':
        return 'remote'
      case 'merge':
        return await this.mergeData(conflict.localData, conflict.remoteData)
      case 'ask':
      default:
        // 在实际应用中，这里应该显示用户界面让用户选择
        // 现在返回默认策略
        return 'local'
    }
  }
  
  // 合并数据
  async mergeData(localData, remoteData) {
    try {
      // 简单的合并策略：保留两个数据源的所有内容
      const merged = { ...localData, ...remoteData }
      
      // 合并数组数据
      if (localData.history && remoteData.history) {
        merged.history = [...localData.history, ...remoteData.history]
        // 去重
        merged.history = merged.history.filter((item, index, self) => 
          index === self.findIndex(t => t.id === item.id)
        )
      }
      
      return merged
    } catch (error) {
      console.error('Failed to merge data:', error)
      return localData // 合并失败时使用本地数据
    }
  }
  
  // 更新本地数据
  async updateLocalData(updates) {
    for (const update of updates) {
      try {
        const storageKey = this.getStorageKey(update.module)
        uni.setStorageSync(storageKey, JSON.stringify(update.data))
      } catch (error) {
        console.error(`Failed to update local ${update.module}:`, error)
      }
    }
  }
  
  // 更新远程数据
  async updateRemoteData(updates) {
    for (const update of updates) {
      try {
        await this.makeRequest('PUT', `/data/${update.module}`, {
          data: update.data,
          timestamp: update.timestamp
        })
      } catch (error) {
        console.error(`Failed to update remote ${update.module}:`, error)
      }
    }
  }
  
  // 获取存储键名
  getStorageKey(module) {
    const keys = {
      trustCards: 'trustCardsData',
      dashboard: 'trustDashboardData',
      branch: 'trustBranchData',
      drag: 'trustDragHistory'
    }
    return keys[module] || `${module}Data`
  }
  
  // 记录同步历史
  recordSyncHistory(status, description, details = {}) {
    const entry = {
      id: Date.now(),
      status: status,
      description: description,
      details: details,
      timestamp: Date.now()
    }
    
    this.syncHistory.unshift(entry)
    
    // 限制历史记录数量
    if (this.syncHistory.length > 100) {
      this.syncHistory = this.syncHistory.slice(0, 100)
    }
    
    // 保存到本地存储
    this.saveSyncHistory()
  }
  
  // 保存同步历史
  saveSyncHistory() {
    try {
      uni.setStorageSync('trustSyncHistory', JSON.stringify(this.syncHistory))
    } catch (error) {
      console.error('Failed to save sync history:', error)
    }
  }
  
  // 获取同步历史
  getSyncHistory() {
    try {
      const history = uni.getStorageSync('trustSyncHistory')
      if (history) {
        this.syncHistory = JSON.parse(history)
      }
    } catch (error) {
      console.error('Failed to load sync history:', error)
    }
    return this.syncHistory
  }
  
  // 获取冲突
  getConflicts() {
    return this.conflicts
  }
  
  // 解决特定冲突
  async resolveSpecificConflict(conflictId, resolution) {
    try {
      const conflict = this.conflicts.find(c => c.id === conflictId)
      if (!conflict) {
        return { success: false, error: '冲突不存在' }
      }
      
      // 根据解决方案更新数据
      if (resolution === 'local') {
        // 使用本地数据
        await this.updateLocalData([{
          module: conflict.type,
          data: conflict.localData,
          timestamp: Date.now()
        }])
      } else if (resolution === 'remote') {
        // 使用远程数据
        await this.updateLocalData([{
          module: conflict.type,
          data: conflict.remoteData,
          timestamp: Date.now()
        }])
      } else if (resolution === 'merge') {
        // 合并数据
        const merged = await this.mergeData(conflict.localData, conflict.remoteData)
        await this.updateLocalData([{
          module: conflict.type,
          data: merged,
          timestamp: Date.now()
        }])
      }
      
      // 从冲突列表中移除
      this.conflicts = this.conflicts.filter(c => c.id !== conflictId)
      
      return { success: true }
    } catch (error) {
      console.error('Failed to resolve conflict:', error)
      return { success: false, error: error.message }
    }
  }
  
  // 开始自动同步
  startAutoSync() {
    if (this.autoSyncInterval) {
      clearInterval(this.autoSyncInterval)
    }
    
    this.autoSyncInterval = setInterval(() => {
      this.syncData()
    }, this.syncSettings.syncInterval)
  }
  
  // 停止自动同步
  stopAutoSync() {
    if (this.autoSyncInterval) {
      clearInterval(this.autoSyncInterval)
      this.autoSyncInterval = null
    }
  }
  
  // 获取同步设置
  async getSyncSettings() {
    try {
      const settings = uni.getStorageSync('trustSyncSettings')
      if (settings) {
        this.syncSettings = { ...this.syncSettings, ...JSON.parse(settings) }
      }
    } catch (error) {
      console.error('Failed to load sync settings:', error)
    }
    return this.syncSettings
  }
  
  // 保存同步设置
  async saveSyncSettings(settings) {
    try {
      this.syncSettings = { ...this.syncSettings, ...settings }
      uni.setStorageSync('trustSyncSettings', JSON.stringify(this.syncSettings))
      
      // 重新启动自动同步
      if (this.syncSettings.autoSync) {
        this.startAutoSync()
      } else {
        this.stopAutoSync()
      }
    } catch (error) {
      console.error('Failed to save sync settings:', error)
      throw error
    }
  }
  
  // 发送请求
  async makeRequest(method, endpoint, data = null) {
    // 如果没有配置服务器，直接返回模拟响应
    if (!this.syncSettings.syncServer) {
      console.log('Sync server not configured, returning mock response')
      return { status: 200, data: { message: 'Server not configured' } }
    }
    
    try {
      const url = `${this.syncSettings.syncServer}${endpoint}`
      const options = {
        url: url,
        method: method,
        header: {
          'Content-Type': 'application/json',
          'Authorization': this.syncSettings.apiKey ? `Bearer ${this.syncSettings.apiKey}` : ''
        }
      }
      
      if (data) {
        options.data = data
      }
      
      return await new Promise((resolve, reject) => {
        uni.request({
          ...options,
          success: (res) => resolve(res),
          fail: (error) => {
            // 静默处理连接失败，不抛出错误
            console.log('Request failed (server unavailable):', error.errMsg)
            resolve({ status: 200, data: { message: 'Server unavailable' } })
          }
        })
      })
    } catch (error) {
      console.log('Request failed (silent):', error)
      // 静默处理错误，返回模拟响应
      return { status: 200, data: { message: 'Request failed' } }
    }
  }
  
  // 导出数据
  exportData() {
    return {
      syncHistory: this.syncHistory,
      conflicts: this.conflicts,
      settings: this.syncSettings,
      lastSyncTime: this.lastSyncTime,
      exportTime: Date.now()
    }
  }
  
  // 导入数据
  async importData(data) {
    try {
      if (data.syncHistory) {
        this.syncHistory = data.syncHistory
        this.saveSyncHistory()
      }
      
      if (data.settings) {
        await this.saveSyncSettings(data.settings)
      }
      
      return true
    } catch (error) {
      console.error('Failed to import data:', error)
      return false
    }
  }
  
  // 清除所有数据
  clearAllData() {
    this.syncHistory = []
    this.conflicts = []
    this.lastSyncTime = null
    
    try {
      uni.removeStorageSync('trustSyncHistory')
      uni.removeStorageSync('trustSyncSettings')
      return true
    } catch (error) {
      console.error('Failed to clear data:', error)
      return false
    }
  }
}

export default new TrustSyncManager()

